﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using QLKDS.DAL;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using QLKDS.DTO;
using QLKDS.Reports;

namespace QLKDS.Forms
{
    public partial class frmImportBooks : XtraForm
    {
        private SupplierManager supplierManager = new SupplierManager();
        private StoreManager storeManager = new StoreManager();
        private BookStoreManager bookStoreManager = new BookStoreManager();
        private BooksManager booksManager=new BooksManager();
        private IList<ImportBookDetailInfo> L_ImportedBookDetailInfo = new List<ImportBookDetailInfo>();
        private ImportBookManager importBookManager;
        private ImportBookDetailManager importBookDetailManager;
     
        public frmImportBooks()
        {
            InitializeComponent();
            this.importBookDetailManager = new ImportBookDetailManager();
            this.importBookManager = new ImportBookManager();
            this.txtDiscountPercent.Text = "0";
            this.txtTotalPrice.Text = "0";
            this.txtDiscount.Text = "0";
            this.txtTax.Text = "0";
        }

        private void LoadSupplier()
        {
            this.lueSupplier.Properties.DataSource = this.supplierManager.ListSupplier();
            this.lueSupplier.Properties.DisplayMember = "Code";
            this.lueSupplier.Properties.ValueMember = "Id";
        }
        private void LoadBook()
        { 
            this.lueBookCode.Properties.DataSource = this.booksManager.ListBook();
            this.lueBookCode.Properties.DisplayMember = "Code";
            
        }
        private void LoadImportedBook()
        {
            this.gridImportedBooks.DataSource =L_ImportedBookDetailInfo;
        }

        private void frmImportedBooks_Load(object sender, EventArgs e)
        {
            this.LoadSupplier();
            this.LoadStore();
            this.LoadBook();

            this.dteImportedDate.DateTime = DateTime.Now;
         
        }
        private void LoadStore()
        {
            this.lueStore.Properties.DataSource = storeManager.ListStore();
            this.lueStore.Properties.DisplayMember = "Name";
            this.lueStore.Properties.ValueMember = "Id";
        }

        private void lueSupplier_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            ButtonEdit editor = (ButtonEdit)sender;
            EditorButton Button = e.Button;
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                var form = new frmSupplierAdd();
                if(form.ShowDialog()==DialogResult.OK)
                {
                    this.LoadSupplier();
                }
            }
        }

        private void lueSupplier_EditValueChanged(object sender, EventArgs e)
        {
            this.txtSupplierName.Text = this.supplierManager.GetSupplierByCode(this.lueSupplier.Text.Trim()).Name;
            this.txtSupplierContactor.Text = this.supplierManager.GetSupplierByCode(this.lueSupplier.Text.Trim()).Contactor;
            this.txtSupplierContactorMobile.Text = this.supplierManager.GetSupplierByCode(this.lueSupplier.Text.Trim()).ContactorMobile;
            this.txtOldLiabilities.Text = this.supplierManager.GetSupplierByCode(this.lueSupplier.Text.Trim()).Liabilities.ToString();
            this.dxepSupplier.ClearErrors();
        }

        private void lueBookCode_EditValueChanged(object sender, EventArgs e)
        {
            this.dxepBookCode.ClearErrors();
            this.txtBookName.Text = this.booksManager.GetBookByCode(this.lueBookCode.Text.Trim()).Name;
            this.txtBookPrice.Text=this.booksManager.GetBookByCode(this.lueBookCode.Text.Trim()).Price.ToString();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.lueSupplier.Text.Trim() == String.Empty)
            {
                this.dxepSupplier.SetError(this.lueSupplier, "Lựa chọn nhà cung cấp");
                this.lueSupplier.Focus();
                return;
            }
            else if (this.lueBookCode.Text.Trim() == string.Empty)
            {
                this.dxepBookCode.SetError(this.lueBookCode, "Lựa chọn sách");
                this.lueBookCode.Focus();
                return;
            }
            else if (this.txtQuanlity.Text==string.Empty)
            {
                this.dxepQuanlity.SetError(this.txtQuanlity, "Kiểm tra số lượng");
                this.txtQuanlity.Focus();
                return;
            }

            try
            {

                var importedBookDetailInfo = new ImportBookDetailInfo();
                importedBookDetailInfo.Id = 1;
                importedBookDetailInfo.BookCode = lueBookCode.Text.Trim();
                importedBookDetailInfo.BookId = this.booksManager.GetBookByCode(this.lueBookCode.Text.Trim()).Id;
                importedBookDetailInfo.BookName = this.txtBookName.Text.Trim();
                importedBookDetailInfo.Price = float.Parse(this.txtBookPrice.Text.Trim());
                importedBookDetailInfo.Quanlity = int.Parse(this.txtQuanlity.Text.Trim());
                importedBookDetailInfo.DiscountPercent = int.Parse(this.txtDiscountPercent.Text.Trim());
                importedBookDetailInfo.TotalPrice = importedBookDetailInfo.Price * importedBookDetailInfo.Quanlity / 100 * (100 - importedBookDetailInfo.DiscountPercent);
                this.TotalPrice(importedBookDetailInfo.TotalPrice);
                L_ImportedBookDetailInfo.Add(importedBookDetailInfo);
                this.LoadImportedBook();
                this.gridImportedBooks.RefreshDataSource();
            }
            catch (Exception)
            {
                
                XtraMessageBox.Show( "Lỗi! Kiểm tra lại dữ liệu","Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void TotalPrice(float price)
        {
            this.txtTotalPrice.Text = (float.Parse(this.txtTotalPrice.Text) + price).ToString();
            this.txtTotalAmount.Text=(float.Parse(this.txtTotalPrice.Text)/100*(100+float.Parse(this.txtTax.Text)-float.Parse(this.txtDiscount.Text))).ToString();
            this.txtPaymentRequest.Text = (float.Parse(this.txtTotalAmount.Text.Trim()) + float.Parse(this.txtOldLiabilities.Text.Trim())).ToString();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmImportBooks_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmMain.MainWindowManager.WindowNames.Remove(this.Name);
            frmMain.MainWindowManager.Windows.Remove(this);
        }

        private void txtQuanlity_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtQuanlity.Text.Trim() != string.Empty)
            {
                this.dxepQuanlity.ClearErrors();
            }

        }

        private void txtCode_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtCode.Text.Trim() != String.Empty)
            {
                this.dxepCode.ClearErrors();
            }
            if (this.importBookManager.HasCodeExisted(this.txtCode.Text.Trim()))
            {
                this.dxepCode.SetError(this.txtCode, "Mã phiếu nhập đã tồn tại");
                this.txtCode.Focus();
                return;
            }
            else
            {
                this.dxepCode.ClearErrors();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.lueSupplier.Text.Trim() == String.Empty)
            {
                this.dxepSupplier.SetError(this.lueSupplier, "Chọn nhà cung cấp");
                this.lueSupplier.Focus();
                return;
            }
            else if (this.txtCode.Text.Trim() == String.Empty)
            {
                this.dxepCode.SetError(this.txtCode, "Nhập mã hóa đơn");
                this.txtCode.Focus();
                return;
            }
            else if (this.importBookManager.HasCodeExisted(this.txtCode.Text.Trim()))
            {
                this.dxepCode.SetError(this.txtCode, "Mã phiếu nhập đã tồn tại");
                this.txtCode.Focus();
                return;
            }
            else if (this.lueStore.Text.Trim() == String.Empty)
            {
                this.dxepStore.SetError(this.lueStore, "Lựa chọn cửa hàng");
                this.lueStore.Focus();
                return;
            }
            else if (this.txtPayment.Text.Trim() == String.Empty)
            {

                this.dxepPayment.SetError(this.txtPayment, "Nhập tiền thanh toán");
                this.txtPayment.Focus();
                return;
            }
            else
            {
                this.dxepCode.ClearErrors();
                this.dxepSupplier.ClearErrors();
                this.dxepStore.ClearErrors();
            }

            try
            {
                //save importBook
                var _importBook = new ImportBook();
                _importBook.Code = this.txtCode.Text.Trim();
                _importBook.ImportDate = this.dteImportedDate.DateTime;
                _importBook.Status = 1;

                _importBook.Tax = int.Parse(this.txtTax.Text.Trim());
                _importBook.TotalAmount = float.Parse(this.txtTotalAmount.Text.Trim());
                _importBook.SupplierId = this.supplierManager.GetSupplierByCode(this.lueSupplier.Text.Trim()).Id;
                _importBook.CreatedBy = "Admin";
                _importBook.CreatedDate = DateTime.Now;
                _importBook.ModifiedBy = "Admin";
                _importBook.ModifiedDate = DateTime.Now;
                this.importBookManager.CreateImportBook(_importBook);

                //save import detail
                foreach (ImportBookDetailInfo item in L_ImportedBookDetailInfo)
                {
                    var _importBookDetail = new ImportBookDetail();
                    _importBookDetail.ImportId = _importBook.Id;
                    _importBookDetail.BookId = item.BookId;
                    _importBookDetail.Price = item.Price;
                    _importBookDetail.Quantity = item.Quanlity;
                    _importBookDetail.DiscountPercent = item.DiscountPercent;
                    _importBookDetail.TotalPrice = item.TotalPrice;
                    _importBookDetail.StoreId = this.storeManager.GetStoreByName(this.lueStore.Text.Trim()).Id;
                    this.importBookDetailManager.CreateImportBookDetail(_importBookDetail);


                    //update quality bookstore
                    var bookSore = this.bookStoreManager.GetBookStore(_importBookDetail.BookId, _importBookDetail.StoreId);
                    bookSore.Quantity += _importBookDetail.Quantity;
                    this.bookStoreManager.UpdateBookStore(bookSore);

                }

                var _supplier = this.supplierManager.GetSupplierByCode(this.lueSupplier.Text.Trim());
                _supplier.Liabilities = float.Parse(this.txtNewLiabilities.Text.Trim());
                supplierManager.UpdateSupplier(_supplier);
                XtraMessageBox.Show("Thành công");
            }
            catch (Exception)
            {

                XtraMessageBox.Show("Lỗi! Kiểm tra lại dữ liệu","Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

          
        }

        private void txtTax_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtDiscount.Text != String.Empty)
            {
                this.txtTotalAmount.Text = (float.Parse(this.txtTotalPrice.Text) / 100 * (100 + float.Parse(this.txtTax.Text) - float.Parse(this.txtDiscount.Text))).ToString();
            }
        }
        private void txtDiscount_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtTax.Text != String.Empty)
            {
                this.txtTotalAmount.Text = (float.Parse(this.txtTotalPrice.Text) / 100 * (100 + float.Parse(this.txtTax.Text) - float.Parse(this.txtDiscount.Text))).ToString();
            }
        }

        private void txtPayment_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtPayment.Text != String.Empty)
            {
                this.txtNewLiabilities.Text = (float.Parse(this.txtPaymentRequest.Text.Trim()) - float.Parse(this.txtPayment.Text.Trim())).ToString();
                this.dxepPayment.ClearErrors();
            }

        }

        private void lueStore_EditValueChanged(object sender, EventArgs e)
        {
            this.dxepStore.ClearErrors();
        }

        private void txtTotalAmount_EditValueChanged(object sender, EventArgs e)
        {
            if (txtTotalAmount.Text.Trim() != String.Empty && this.txtOldLiabilities.Text.Trim() != String.Empty)
            {
                this.txtPaymentRequest.Text = (float.Parse(this.txtTotalAmount.Text.Trim()) + float.Parse(this.txtOldLiabilities.Text.Trim())).ToString();
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            ImportReport rpt = new ImportReport();
            rpt.ShowPreviewDialog();
        }






    }
}